import functools

from flask import (Blueprint, flash, g, redirect, render_template, request, session, url_for)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

# 创建 蓝图 对象，指定名称和 url 前缀
bp = Blueprint('auth', __name__, url_prefix='/auth')


# 视图方法，对应注册页面
@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        if not username:
            error = '用户名不能为空！'
        elif not password:
            error = '密码不能为空！'
        elif db.execute(
                'SELECT id FROM user  WHERE username = ?', (username,)
        ).fetchone() is not None:
            error = '用户名{}已存在。'.format(username)

        if error is None:
            db.execute(
                'INSERT INTO user (username, password) VALUES (?, ?)',
                (username, generate_password_hash(password))
            )
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')


# 登录页视图方法
@bp.route('/login', methods=('GET', 'POST'))
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute(
            'SELECT * FROM user WHERE username = ?', (username,)
        ).fetchone()

        if user is None:
            error = '用户名不存在'
        elif not check_password_hash(user['password'], password):
            error = '密码错误'

        if error is None:
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/login.html')


# 注销视图方法
@bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('index'))


# 每次请求前都执行用户缓存判断
@bp.before_app_request
def load_logged_in_user():
   user_id = session.get('userid')

   if user_id is None:
       g.user = None
   else:
       g.user = get_db().execute(
           'SELECT * FROM user WHERE id = ?', (user_id,)
       ).fetchone()


# 认证需求修饰器
def login_required(view):
    @functools.wraps(view)
    def warapped_view(**kwargs):
        if g.user is None:
            return  redirect(url_for('auth.login'))

        return view(**kwargs)

    return warapped_view

